// 接收来自后台的消息
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse){
	if(request){
		switch(request.cmd){
			case 'tmall':
				if (request.data) {
					if (request.data.status === 'fail'){
						tip(request.data.errMsg);
					}else{
						tip('保存成功，图片已存至：' + request.data.data.path, true);
					}
				} else {
					tip(request.errMsg || '保存失败');
				}
				break;
		}
	}
});

// 简单的消息通知
var tipCount = 0;
function tip(info, closable) {
	info = info || '';
	var ele = document.createElement('div');
	ele.className = 'chrome-plugin-simple-tip slideInLeft';
	ele.style.top = tipCount * 50 + 20 + 'px';
	ele.innerHTML = `<div>${info}<span class="close">×</span></div>`;
	document.body.appendChild(ele);
	ele.classList.add('animated');
	tipCount++;
	if (!closable) {
		setTimeout(() => {
			ele.style.top = '-100px';
			setTimeout(() => {
				ele.remove();
				tipCount--;
			}, 200);
		}, 5000);
	}
	$(ele).on('click', '.close', ()=>{
		ele.style.top = '-100px';
		setTimeout(() => {
			ele.remove();
			tipCount--;
		}, 200);
	})
}

// 简单的消息提示
function showToast(msg, duration = 5000){
	if(!msg) return false;
	var html = `
		<div class="zp-simple-tip">
			<span class="wraper">${msg}</span>
		</div>
	`;
	$('body').append($(html));
	setTimeout(()=>{
		$('.zp-simple-tip').remove();
	}, duration)
}

// 去除图片时间戳
function removeTimestamp(url){
	return url.split('?')[0];
}

// 获取天猫套图
function getTmallPics(request){
	// 详情图
	let detailPics = [...$('#description .content img')]
		.map(v => {
			v = v.getAttribute('src');
			if(v.indexOf('?time=')>0){
				v = removeTimestamp(v);
			}
			if(v.indexOf('https://')===-1){
				v = 'https:' + v;
			}
			return v;
		});

	if(detailPics.length === 0) {
		tip('请滚动到页面底部！');
		return false;
	}

	// 保存的文件名
	const name = request.data.name;

	// 主图
	let mainPics = [...$('#J_UlThumb img')].map(v=>{
			let reg = /^\/\/img\.alicdn\.com\/imgextra\/(.+)_60x60q90\.jpg$/;
			let src = v.getAttribute('src');
			if(src.indexOf('https://')>-1){
				src = reg.exec(src)[1];
			}else{
				reg = /^(.+)_60x60q90\.jpg$/;
				src = 'https:' + reg.exec(src)[1];
			}
			return src;
	});
	
	// 分类图
	let catePics = [...$('.J_TSaleProp li:not(.tb-txt) a')]
		.filter(v=>v.getAttribute('style'))
		.map(v=>{
			const reg = /^background:url\((.+)_[0-9]{2,3}x[0-9]{2,3}q90\.jpg\) center no-repeat;$/;
			let src = v.getAttribute('style');
			let name = $(v).find('span').text().replace(/[\/\*\?\"“\'‘]/g, ' ');
			src = 'https:' + reg.exec(src)[1] + '_800x800.jpg';
			return {src, name};
		});
	if (catePics.length === 0) {
		let pics = $('.J_TSaleProp li a');
		for(let i=0; i<pics.length; i++){
			const reg = /^(.+)_[0-9]{2,3}x[0-9]{2,3}q90\.jpg$/;
			const name = $(pics[i]).find('span').text().replace(/[\/\*]/g, ' ');
			pics[i].click();
			let src = $('#J_ImgBooth').attr('src');
			catePics.push({
				src: 'https:' + reg.exec(src)[1] + '_800x800.jpg',
				name
			});
		}
	}

	const props = getItemProps();
	
	sendMessageToBackground({
		cmd: 'tmall',
		data: {
			name,
			mainPics,
			catePics,
			detailPics,
			...props
		}
	})
}
// 获取宝贝相关属性
function getItemProps(){
	const propsEle = $('#J_AttrUL li');
	const strFilter = (index) => {
		if(!propsEle[index]) return '';
		return $(propsEle[index]).text().split(':')[1].trim();
	};
	const brand = strFilter(4);
	const model = strFilter(5).split('/');
	const style = strFilter(8);
	const title = $('.tb-detail-hd h1').text().trim();
	const material = strFilter(2);
	return {
		material, brand, model, style, title
	}
}

// 主动发送消息给后台background
// 要演示此功能，请打开控制台主动执行sendMessageToBackground()
function sendMessageToBackground(options) {
	chrome.runtime.sendMessage(options, function(response) {
		// console.log(response)
	});
}

// 保存套图主程序
const main = () => {
	let root = localStorage.getItem('__xyroot__');
	let modelRoot = localStorage.getItem('__xymodelroot__');
  let html = `
		<div id="zp-save-single-pic-wraper">
			<h2>保存套图</h2>
			<input id="aSet" placeholder="根目录" value="${root ? root : ''}" />
			<input id="aSetModel" placeholder="型号目录" value="${modelRoot ? modelRoot : ''}" />
			<button id="saveASetPicBtn">存为套图</button>
			<div class="divider"></div>
			<h2>保存单张主图</h2>
      <input class="src" id="singleSrc" placeholder="图片地址" />
      <input class="dir" id="singleDir" placeholder="型号目录" value="${root ? root : ''}${modelRoot ? modelRoot : ''}" /><br />
			<button id="saveSinglePicBtn">保存单张主图</button>
			<span class="hide-btn" title="隐藏/显示"></span>
    </div>
  `;
	$('body').append($(html));

	let aSetModel = $('#aSetModel');
	let singleDir = $('#singleDir');

	$('#saveSinglePicBtn').on('click', function(){
		let src = $('#singleSrc');
		let dir = $('#singleDir');
		if(!src.val()){
			tip('图片路径不能为空！');
			return false;
		}
		if(!dir.val()){
			tip('型号目录不能为空！');
			return false;
		}
		sendMessageToBackground({
			cmd: 'single',
			data: {
				src: src.val().replace(/(\.jpg_)180x180(\.jpg)$/, '$1800x800$2'),
				dir: dir.val()
			}
		});
	});
	$('#zp-save-single-pic-wraper .hide-btn').on('click', function(){
		$(this).parent().toggleClass('hide');
	});
	$('#aSet').on('change', function(){
		let val = $(this).val();
		localStorage.setItem('__xyroot__', val);
		singleDir.val(val + aSetModel.val());
		root = val;
	})
	aSetModel.on('input', function(){
		let val = $(this).val();
		localStorage.setItem('__xymodelroot__', val);
		singleDir.val(root + $(this).val());
		modelRoot = val;
	})
	$('#saveASetPicBtn').on('click', function(){
		let href = location.href;
		if ( href.indexOf('https://detail.tmall.com/item.htm') === -1 ) {
			tip('非详情页无法保存！')
			return false;
		}
		let name = aSetModel.val();
		if (!name) {
			tip('【型号目录】不能为空');
			return false;
		}
		getTmallPics({
			type: 'tmall',
			data: {
				name: $('#aSet').val() + name
			}
		});
	})
};
main();
